package com.tianma315.admin.device.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.CoreServiceImpl;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.common.utils.DateUtils;
import com.tianma315.admin.device.domain.DeviceTypeDO;
import com.tianma315.admin.device.service.DeviceTypeService;
import com.tianma315.admin.device.vo.DeviceAndTypeVO;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tianma315.admin.device.dao.DeviceDao;
import com.tianma315.admin.device.domain.DeviceDO;
import com.tianma315.admin.device.service.DeviceService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 
 * <pre>
 * 设备表
 * </pre>
 * <small> 2019-05-22 16:08:48 | Aron</small>
 */
@Service
public class DeviceServiceImpl extends CoreServiceImpl<DeviceDao, DeviceDO> implements DeviceService {
    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Override
    public Page<DeviceAndTypeVO> getDeviceAndTypeVOPage(Integer pageNumber, Integer pageSize, DeviceDO deviceDTO) {
        // 查询列表数据
        Page<DeviceAndTypeVO> page = new Page<>(pageNumber, pageSize);
        List<DeviceAndTypeVO> list = deviceDao.getDeviceAndTypeVOList(page,deviceDTO);
        page.setRecords(list);
//        page.setTotal(list.size());
        return page;
    }

    @Override
    public boolean addDeviceDO(DeviceDO deviceDO) {
        deviceDO.setState(0);
        return insert(deviceDO);
    }

    @Override
    public boolean deleteDeviceDO(Integer id) {
        DeviceDO deviceDO = new DeviceDO();
        deviceDO.setDeviceId(id);
        deviceDO.setState(1);
        return updateById(deviceDO);
    }

    @Override
    public HSSFWorkbook exportDevice() {
        String[] title = {"设备名称","型号","生产厂家","使用车间","投入使用时间(格式2019/1/1)","数量","设备类型","备注","材质"};
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("设备导入");

        sheet.addMergedRegion(new CellRangeAddress(0,0,0,8));//第一行第一列开始，跨8列
        HSSFRow titleRow = sheet.createRow(0);//第0行

        //标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short)18);
        titleStyle.setFont(font);

        //生成标题
        HSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("设备导入模板（红色标识列为必填）");
        titleCell.setCellStyle(titleStyle);

        //红色字体
        HSSFCellStyle redStyle = wb.createCellStyle();
        redStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont redFont = wb.createFont();
        redFont.setBold(true);
        redFont.setColor(Font.COLOR_RED);
        redStyle.setFont(redFont);

        //默认字体样式
        HSSFCellStyle defaultStyle = wb.createCellStyle();
        defaultStyle.setAlignment(HorizontalAlignment.CENTER);
        HSSFFont defaultFont = wb.createFont();
        defaultFont.setBold(true);
        defaultStyle.setFont(defaultFont);

        //声明列对象
        HSSFCell cell = null;
        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        for(int i=0;i<title.length;i++){
            //下标为6时说明是 备注，备注不用加红丝字体样式
            if (i == 7){
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(defaultStyle);
            }else{
                cell = headRow.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(redStyle);
            }
        }

        List<DeviceTypeDO> list = deviceTypeService.getDeviceTypeDOList();
        String[] deviceTypeArr = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            deviceTypeArr[i] = list.get(i).getTypeName();
        }
        //设置设备类型为下拉框选项
        DVConstraint constraint = DVConstraint
                .createExplicitListConstraint(deviceTypeArr);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(2,
                10000, 6, 6);
        HSSFDataValidation data_validation_list = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(data_validation_list);
        return wb;
    }

    @Override
    public void importDevice(MultipartFile file,Long userId) {
        Boolean flag = isExcel(file.getOriginalFilename());
        if (!flag)
            throw new MessageException("只支持Excel文件");

        try {
            HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum(); //返回行数下标 从0开始
            //前两行都不是内容，所以从2开始
            for (int i = 2; i <= rowNum; i++) {
                Row row = sheet.getRow(i);
                short num = row.getLastCellNum();

                DeviceDO deviceDO = new DeviceDO();
                deviceDO.setCreateDate(new Date());
                deviceDO.setCreateBy(userId);
                deviceDO.setState(0);
//                for (int j = 0; j < num; j++) {
                Cell deviceNameCell = row.getCell(0);
                if (isCellEmpty(deviceNameCell))
                    throw new MessageException("设备名称不能为空");
                deviceDO.setDeviceName(deviceNameCell.getStringCellValue());

                Cell signalCell = row.getCell(1);
//                signalCell.setCellType(CellType.STRING);
                if (isCellEmpty(signalCell))
                    throw new MessageException("型号不能为空");
                deviceDO.setSignal(signalCell.getStringCellValue());

                Cell produceFactoryCell = row.getCell(2);
                if (isCellEmpty(produceFactoryCell))
                    throw new MessageException("生产厂家不能为空");
                deviceDO.setProduceFactory(produceFactoryCell.getStringCellValue());

                Cell useFarmCell = row.getCell(3);
                if (isCellEmpty(useFarmCell))
                    throw new MessageException("使用车间不能为空");
                deviceDO.setUseFarm(useFarmCell.getStringCellValue());

                Cell useDateCell = row.getCell(4);
                if (useDateCell == null || useDateCell.getDateCellValue() == null)
                    throw new MessageException("使用时间不能为空");
                deviceDO.setUseDate(useDateCell.getDateCellValue());

                Cell numberCell = row.getCell(5);
                if (isCellEmpty(numberCell))
                    throw new MessageException("数量不能为空");
                deviceDO.setNumber(Integer.parseInt(numberCell.getStringCellValue()));

                Cell deviceTypeCell = row.getCell(6);
                if (isCellEmpty(deviceTypeCell))
                    throw new MessageException("类型不能为空");
                List<DeviceTypeDO> deviceTypeDOList = deviceTypeService.getDeviceTypeByName(deviceTypeCell.getStringCellValue());
                if (deviceTypeDOList == null || deviceTypeDOList.isEmpty()){
                    throw new MessageException("未在数据库中找到此设备类型，请重新生成模板");
                }
                deviceDO.setDeviceTypeId(deviceTypeDOList.get(0).getDeviceTypeId());

                Cell markCell = row.getCell(7);
                if (!isCellEmpty(markCell)){
                    deviceDO.setMark(markCell.getStringCellValue());
                }

                Cell qualityCell = row.getCell(8);
                if (isCellEmpty(qualityCell))
                    throw new MessageException("材质不能为空");
                deviceDO.setQuality(qualityCell.getStringCellValue());

                insert(deviceDO);
            }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Boolean isExcel(String fileName){
        Boolean flag;
        String[] nameArray =  fileName.split("\\.");
        Integer index =nameArray.length - 1;
        String name  = nameArray[index];
        if ("xls".equals(name)){
            flag = true;
        }else if("xlsx".equals(name)){
            flag = true;
        }else if("xlsm".equals(name)){
            flag = true;
        }else{
            flag = false;
        }
        return flag;
    }

    public Boolean isCellEmpty(Cell cell){
        if (cell == null){
            return true;
        }else{
            cell.setCellType(CellType.STRING);
            if (cell.getStringCellValue()==null){
                return true;
            }else{
                return false;
            }
        }

    }
}
